import Vue from "vue";
import VueRouter from "vue-router";
import Register from "@/views/Register.vue";
import Login from "@/views/Login.vue";
import Userinfo from "@/views/Userinfo.vue";
import Edit from "@/views/Edit.vue";
import Home from "@/views/Home.vue";
import ArticleDetails from "@/views/ArticleDetails.vue";

Vue.use(VueRouter);

const routes = [
  {
    path:"/",
    redirect:"/home",
  },
  {
    path:"/home",
    component:Home,
    meta:{keepAlive:true} /* 用于检测当前路由是否需要维持状态不销毁 */
  },
  {
    path:"/article_details/:id",
    component:ArticleDetails,
  },
  {
    path:"/register",
    component:Register
  },
  {
    path:"/login",
    component:Login
  },
  {
    path:"/userinfo",
    component:Userinfo,
    meta:{testToken:true} /* 用于检测当前路由是否需要登录权限 */
  },
  {
    path:"/edit",
    component:Edit,
    meta:{testToken:true}
  },
];

const router = new VueRouter({
  mode:"history",
  routes,
});

/* 全局导航前置守卫(路由拦截) */
router.beforeEach((to,from,next)=>{
  // 当需要登录权限时(meta.testToken==true)，判断是否登录
  if (to.meta.testToken === true && !localStorage.getItem("id") && !localStorage.getItem("token")) {
    Vue.prototype.$toast.fail("请先登录");
    next('/login')
    return
  }
  next()
})

export default router;
